package com.bancstone.common;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.LongBuffer;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * Project: GitTest <br/>
 * Class: com.bancstone.common.StringUtils <br/>
 * Description: 字符类共同方法. <br/>
 * Copyright: Copyright (c) 2015 <br/>
 * Makedate: 2015年3月2日 下午2:56:50 <br/>
 * 
 * @author guanxiaolin
 * @version 1.0
 * @since 1.0
 */
public class StringUtils {

	public static final String HEX_CHARS = "0123456789ABCDEF";

	/**
	 * 所有表示金额的字段
	 */
	public final static String[] mountUtils = { "Amount", "ServiceCharge", "Postage", "OutstationCharge", "CtrlSum",
			"OrnglCtrlSum", "TotalAmt", "AgncyCharge", "AclmtAmt", "SucflTxsAmt", "SnglAmt", "SucflRspedTxsAmt",
			"SndTtlAmt", "RcvTtlAmt", "AmtLmt", "CdtLd", "TtlPldgVal", "CdtXtnsnLmt", "NetDbtLmt", "AvlblNetDbt",
			"AvlblNetDbtWrngVal", "DstrbtnPldgVal", "OrgnlNotDstrbtn", "OrgnlIsDstrbtn", "NotDstrbtn", "IsDstrbtn",
			"ForceDwn", "SndCtrlSum", "RcvCtrlSum", "TtlAmt", "SndgTtlAmt", "CptlAmt", "AccrlAmt", "DtlSmmryAmt",
			"AmndsAmt", "RjctAmt", "OrgnlAmt", "PmtAmt", "OddAmt", "SNDBKCHRG", "RCVBKCHRG", "NOTESAMT", "PREMIUM",
			"GONGBENFEI", "ISSUEAMT" };

	/**
	 * 
	 * <ul>
	 * <li>2、开发日期：Jul 22, 2010</li>
	 * <li>3、开发时间：12:56:46 AM</li>
	 * <li>4、返回类型：String</li>
	 * <li>5、方法含义：</li>
	 * <li>6、方法说明：将对象转换为字符串</li>
	 * </ul>
	 * 
	 * @param object
	 * @return
	 */
	public static String toString(Object object) {
		return StringUtils.toString(object, -1);
	}

	/**
	 * 
	 * <ul>
	 * <li>2、开发日期：Jul 22, 2010</li>
	 * <li>3、开发时间：12:57:51 AM</li>
	 * <li>4、返回类型：String</li>
	 * <li>5、方法含义：</li>
	 * <li>6、方法说明：将对象转换为字符串</li>
	 * </ul>
	 * 
	 * @param object
	 * @param maxItems
	 * @return
	 */
	private static String toString(Object object, int maxItems) {
		if (object == null) {
			// return "null";
			return " ";
		}

		if (object instanceof String) {
			return ("\"" + object + "\"").replace("\"", "");// 双引号"转换为""
		}

		if ((object instanceof Character) || (object.getClass() == Character.TYPE)) {
			return ("'" + object + "'");
		}

		if (object instanceof Number) {
			if ((object instanceof Byte) || (object instanceof Short) || (object instanceof Integer)
					|| (object instanceof Long)) {
				// return object + " <0x"
				// + StringUtils.toHexString((Number) object) + ">";
				return String.valueOf(object);
			}
			return String.valueOf(object);
		}

		if (object.getClass().isArray()) {
			Class<?> type = object.getClass().getComponentType();

			if (maxItems < 0) {
				if (type.isPrimitive()) {
					if (type == Byte.TYPE) {
						return Arrays.toString((byte[]) object);
					}
					if (type == Character.TYPE) {
						return Arrays.toString((char[]) object);
					}
					if (type == Integer.TYPE) {
						return Arrays.toString((int[]) object);
					}
					if (type == Double.TYPE) {
						return Arrays.toString((double[]) object);
					}
					if (type == Long.TYPE) {
						return Arrays.toString((long[]) object);
					}
					if (type == Float.TYPE) {
						return Arrays.toString((float[]) object);
					}
					if (type == Short.TYPE) {
						return Arrays.toString((short[]) object);
					}
					if (type == Boolean.TYPE) {
						return Arrays.toString((boolean[]) object);
					}
					// 永远不会发生
					return "[未知原始类型数组：" + type + "]";
				}
				return Arrays.toString((Object[]) object);
			}

			final int max = Math.min(maxItems, Array.getLength(object));
			List<Object> list = new ArrayList<Object>(max);

			for (int index = 0; index < max; index++) {
				list.add(Array.get(object, index));
			}
			if (max < Array.getLength(object)) {
				list.add("(first " + max + '/' + Array.getLength(object) + " elements only...)");
			}

			object = list;
		} else if ((object instanceof Collection) && (maxItems >= 0)) {

			Collection<?> collection = (Collection<?>) object;
			final int max = Math.min(maxItems, collection.size());
			List<Object> list = new ArrayList<Object>(max);

			int index = 0;
			for (Object item : collection) {
				if (index >= max) {
					list.add("(first " + max + '/' + collection.size() + " elements only...)");
					break;
				}
				list.add(item);
				index++;
			}

			object = list;
		} else if ((object instanceof Map) && (maxItems >= 0)) {
			Map<?, ?> map = (Map<?, ?>) object;
			final int max = Math.min(maxItems, map.size());
			Map<Object, Object> copy = new HashMap<Object, Object>(max);

			int index = 0;
			for (Map.Entry<?, ?> item : map.entrySet()) {
				if (index >= max) {
					copy.put("(first " + max + '/' + map.size() + " elements only...)", "...");
					break;
				}
				copy.put(item.getKey(), item.getValue());
				index++;
			}

			object = copy;
		}

		return String.valueOf(object);
	}

	/**
	 * 
	 * <ul>
	 * <li>2、开发日期：Jul 22, 2010</li>
	 * <li>3、开发时间：12:59:54 AM</li>
	 * <li>4、返回类型：String</li>
	 * <li>5、方法含义：</li>
	 * <li>6、方法说明：将数字转换为16进制字符串</li>
	 * </ul>
	 * 
	 * @param number
	 * @return
	 */
	public static String toHexString(Number number) {
		if (number == null) {
			return "null";
		}

		byte[] bytes = new byte[8];
		ByteBuffer bytesBuffer = ByteBuffer.wrap(bytes);
		LongBuffer longBuffer = bytesBuffer.asLongBuffer();
		longBuffer.put(0, number.longValue());

		StringBuilder stringBuilder = new StringBuilder(16);
		for (int index = 0; index < bytes.length; index++) {
			int b = bytes[index] & 0xFF;
			if ((b != 0) || (stringBuilder.length() > 0) || (index == (bytes.length - 1))) {
				stringBuilder.append(StringUtils.HEX_CHARS.charAt(b >> 4)).append(
						StringUtils.HEX_CHARS.charAt(b & 0x0F));
			}
		}
		return stringBuilder.toString();
	}

	/**
	 * null转变成空
	 * 
	 * @param resource
	 * @return
	 */
	public static String nullToString(String resource) {
		if (resource == null) {
			resource = "";
		} else if (resource.equals("null")) {
			resource = "";
		}
		return resource.trim();
	}

	/**
	 * "" 转变成0
	 * 
	 * @param resource
	 * @return
	 */
	public static short nullToShort(String resource) {
		short s = 0;
		if (resource == null)
			resource = "";
		if (resource.trim().equals(""))
			s = 0;
		else
			s = new Short(resource);
		return s;
	}

	/**
	 * "" 转变成0
	 * 
	 * @param resource
	 * @return
	 */
	public static double nullToDouble(String resource) {
		double s = 0.0;
		if (resource == null)
			resource = "";
		if (resource.trim().equals(""))
			s = 0;
		else
			s = new Double(resource);
		return s;
	}

	/**
	 * null转变成0
	 * 
	 * @param resource
	 * @return
	 */
	public static String nullToZero(String resource) {
		if (resource == null)
			resource = "0";
		if (resource.equals(""))
			resource = "0";
		return resource;
	}

	public static String ridName(String fileName) {
		String returnName = "";
		int pot = fileName.lastIndexOf(".");
		returnName = fileName.substring(pot, fileName.length());
		return returnName;
	}

	/**
	 * convert a string array into a string, each element in array will be delimited by "," if an array = {"0000",
	 * "1111", "2222"}, the return string will be : 0000,1111,2222
	 * 
	 * @param values
	 *            string array
	 * @return converted string, if values is null, null will be return
	 * 
	 */
	public static String strArrayToString(String[] values) {
		if (values == null)
			return "";

		int i = 0, length = values.length;
		String str = "";
		for (i = 0; i < length; i++) {
			str += values[i];
			if (i != length - 1) {
				str += ",";
			}
		}
		return str;
	}

	/**
	 * 分割字串
	 * 
	 * @param source
	 *            原始字符
	 * @param delim
	 *            分割符
	 * @return 字符串数组
	 */
	public static String[] split(String source, String delim) {
		int i = 0;
		int l = 0;
		if (source == null || delim == null)
			return new String[0];
		if (source.equals("") || delim.equals(""))
			return new String[0];

		StringTokenizer st = new StringTokenizer(source, delim);
		l = st.countTokens();
		String[] s = new String[l];
		while (st.hasMoreTokens()) {
			s[i++] = st.nextToken();
		}
		return s;
	}

	/**
	 * 
	 * <ul>

	 * <li>2、开发日期：Sep 10, 2010</li>
	 * <li>3、开发时间：2:41:14 PM</li>
	 * <li>4、返回类型：String</li>
	 * <li>5、方法含义：</li>
	 * <li>6、方法说明：根据原始字符串、指定数据中的元素及指定要返回的数组的长度返回目标数组</li>
	 * </ul>
	 * 
	 * @param source
	 * @param delim
	 * @param length
	 * @param putitem
	 * @return
	 */
	public static String[] arrayConcat(String source, String delim, int newArraylength, String putitem) {
		if (source == null || delim == null)
			return new String[0];
		if (source.equals("") || delim.equals(""))
			return new String[0];
		StringBuffer buffer = new StringBuffer(source);
		for (int i = 0; i < (newArraylength - (source.split(delim).length)); i++) {
			buffer.append("," + putitem);
		}
		// System.out.println(buffer.toString());
		return buffer.toString().split(delim);
	}

	/**
	 * 
	 * <ul>
	 * <li>2、开发日期：Sep 1, 2010</li>
	 * <li>3、开发时间：2:40:55 PM</li>
	 * <li>4、返回类型：String</li>
	 * <li>5、方法含义：</li>
	 * <li>6、方法说明：字符串连接(去除相同的元素)</li>
	 * </ul>
	 * 
	 * @param string
	 * @param string2
	 * @param delim
	 * @return
	 */
	public static String stringConcat(String string, String string2, String delim) {
		String reslut = StringUtils.nullToString(string);
		String[] tempStrings = StringUtils.split(string2, delim);

		if ("".equals(reslut)) {
			for (int i = 0; i < tempStrings.length; i++) {
				reslut += tempStrings[i] + ",";
			}
			if (!"".equals(StringUtils.nullToString(reslut))) {
				reslut = reslut.substring(0, reslut.lastIndexOf(","));
			}
		} else {
			if (reslut.endsWith(",")) {// 去掉末尾的逗号
				reslut = reslut.substring(0, reslut.lastIndexOf(","));
			}
			List<String> tepList = new ArrayList<String>();
			String[] temp = StringUtils.split(reslut, ",");

			for (String string3 : temp) {// 循环添加权限值到List中
				if (!"".equals(StringUtils.nullToString(string3))) {
					tepList.add(string3.trim());
				}
			}

			if (tepList != null && tepList.size() > 0) {

				for (int i = 0; i < tempStrings.length; i++) {
					System.out.println("第  " + i + "  个元素【 " + tempStrings[i] + " 】");

					if (!"".equals(StringUtils.nullToString(tempStrings[i]))) {
						if (!tepList.contains(tempStrings[i].trim())) {
							System.out.println("第  " + i + "  个元素【 " + tempStrings[i] + " 】未找到匹配数据");

							reslut += "," + tempStrings[i];

							System.out.println("第  " + i + "  个元素【 " + tempStrings[i] + " 】追加成功");
						}
					}
				}
			}
		}
		return reslut;
	}

	/**
	 * String [] allProc = new String[]{"1","2","3","4","5","6","7","8"}; String newProc = "1,2,3,4";
	 * 
	 * return new String[]{"5","6","7","8"};
	 * 
	 * @param newProc
	 * @param allProc
	 * @return
	 */
	@SuppressWarnings("unused")
	private static String[] checkProc(String newProc, String[] allProc) {
		String result = "";
		for (int i = 0; i < allProc.length; i++) {
			int g = newProc.indexOf(allProc[i]);
			if (g == -1) {
				result = result + allProc[i] + ",";
			}
		}
		if (result.equals(""))
			return null;
		return result.split(",");
	}

	/**
	 * list 变 string ,添加分隔符 '|'
	 * 
	 * return "a|b|c|d|e|f|g|";
	 * 
	 * @param list
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String listToString(List list) {
		String returnSource = "";
		Iterator it = list.iterator();
		while (it.hasNext()) {
			returnSource = returnSource + toString((List) it.next()) + "\n";
		}
		return returnSource;
	}

	@SuppressWarnings("rawtypes")
	public static String toString(List list) {
		String source = "";
		Iterator it = list.iterator();
		while (it.hasNext()) {
			source = source + it.next() + "|";
		}
		return source;
	}

	// 数组转换，把 一纬数组 转换成 2纬数组
	// new String{"1","2","3","4"};
	// return newString[][]{{"1"},{"2"},{"3"},{"4"}}
	public static String[][] getArray(String[] name) {
		int length = name.length;
		String[][] outValue = new String[length][1];
		for (int i = 0; i < length; i++) {
			outValue[i][0] = name[i];
		}
		return outValue;
	}

	public static String getRidLast(String resource, int dot) {
		if (!resource.equals("")) {
			resource = resource.substring(0, resource.length() - dot);
		}
		return resource;
	}

	public static String ridArg(String source, String prefix) {
		if (nullToString(source).equals(""))
			source = "";
		if (source.startsWith(prefix)) {
			source = source.substring(prefix.length(), source.length());
		}
		return source;
	}

	/**
	 * 处理日期 字符串 把 2007-09-11 转换成 20070911
	 */
	public static String changeDate(String source) {

		if (nullToString(source).equals(""))
			return source;
		if (source.length() < 9)
			return source;
		String returnValue = "";
		returnValue = source.substring(0, 4) + source.substring(5, 7) + source.substring(8, 10);
		return returnValue;
	}

	public static Object stringToInteger(String source) {
		if (nullToString(source).equals("")) {
			return "";
		} else {
			return new Integer(source.trim());
		}
	}

	/**
	 * 去掉 横杠 2007-08 得到 200708
	 * 
	 * @return
	 */
	public static String getRidMonth(String source) {
		if (nullToString(source).equals(""))
			return "";
		if (source.trim().length() == 6)
			return source;
		source = source.substring(0, 4) + source.substring(5, 7);
		return source;
	}

	/**
	 * 为检查null值，如果为null，将返回一位空格的字符串" "，不为空时返回其值
	 * 
	 * @param strn
	 * @return
	 * 
	 * @pdOid a9ab0da9-e381-4966-b48e-d48c5abe32f3
	 */
	public static String objToMoney(String dou) {
		DecimalFormat dFormat = new DecimalFormat("#,##0.00");
		String strn = "0.00";
		if (dou != null) {
			Double d = Double.valueOf(dou);
			strn = dFormat.format(d);
		}
		return strn;
	}

	/**
	 * 给给定的字符串补齐给定位数的空的字符串（空字符串全补0，非空字符串缺几位左对齐补几位）
	 * 
	 * @param strn
	 * @return
	 * 
	 * @pdOid a9ab0da9-e381-4966-b48e-d48c5abe32f3
	 */
	public static String getNullString(String strn, int appointLength) {
		StringBuffer str = new StringBuffer();
		if (strn == null)
			for (int i = 0; i < appointLength; i++) {
				str.append(" ");
			}
		else {
			int count = appointLength - strn.trim().length();
			for (int i = 0; i < count; i++) {
				str.append(" ");
			}
			str.append(strn.trim());
		}

		return str.toString();
	}

	/**
	 * 得到当前时间，并在日期和当前时间中间加字母"T"区分
	 * 
	 * @param strn
	 * @return
	 * 
	 * @pdOid a9ab0da9-e381-4966-b48e-d48c5abe32f3
	 */
	public static String getCurrTime() {
		String strn = "";
		String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
		String nowTime = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
		strn = nowDate + "T" + nowTime;
		return strn;
	}

	/**
	 * 将整数转化为指定长度字符串 exp:1 --> 00001 (lpMaxLength为5)
	 * 
	 * @param lpInt
	 * @param lpMaxLength
	 * @return
	 * 
	 * @pdOid fe6ac6f6-a63e-4c8c-85d0-4cf0abf013ec
	 */
	public static String intToString(int lpInt, int lpMaxLength) {
		int length, i;
		String returnValue = "";

		length = Integer.toString(lpInt).length();
		if (length < lpMaxLength) {
			i = lpMaxLength - length;
			while (i > 0) {
				returnValue = returnValue + "0";
				i--;
			}
			returnValue = returnValue + Integer.toString(lpInt);
		} else {
			returnValue = Integer.toString(lpInt);
		}
		return returnValue;
	}

	/**
	 * 将整数转化为指定长度字符串 exp:1 --> 00001 (lpMaxLength为5)
	 * 
	 * @param lpInt
	 * @param lpMaxLength
	 * @return
	 * 
	 * @pdOid fe6ac6f6-a63e-4c8c-85d0-4cf0abf013ec
	 */
	public static String longToString(long lpInt, int lpMaxLength) {
		int length, i;
		String returnValue = "";

		length = Long.toString(lpInt).length();
		if (length < lpMaxLength) {
			i = lpMaxLength - length;
			while (i > 0) {
				returnValue = returnValue + "0";
				i--;
			}
			returnValue = returnValue + Long.toString(lpInt);
		} else {
			returnValue = Long.toString(lpInt);
		}
		return returnValue;
	}

	public static void main(String[] a) {
		System.out.println(StringUtils.sbuStringByEncodedByteAddSplit("慰藉我危机巍峨哦哦哦交流俩", "...", 16, "GBK"));
	}

	/**
	 * 
	 * 描述 : 去除以-开始或以-结束的字符串. <br/>
	 * <p>
	 * 
	 * @param str
	 * @return
	 */
	public static String subStr(String str) {

		String returnStr = str;

		if ("".equals(StringUtils.nullToString(str))) {
			return "";
		}

		if (str.startsWith("-")) {
			returnStr = str.substring(1, str.length());
		} else if (str.endsWith("-")) {
			returnStr = str.substring(0, str.length() - 1);
		}
		return returnStr;
	}

	/**
	 * 金额 显示小数点 300 －> 3.00
	 * 
	 * @return
	 */
	public static String getAmount(String source) {
		int len = source.length();
		String bstr = "";
		String estr = "";
		if (len > 2) {
			bstr = source.substring(0, source.length() - 2);
			estr = source.substring(source.length() - 2, source.length());
			source = bstr + "." + estr;
		} else if (len == 2) {
			source = "0." + source;
		} else {
			source = "0.0" + source;
		}
		return source;
	}

	/**
	 * 取字符串的前16位，纸票票据号码,如果票据号码长度小于16位，返回""字符串
	 * 
	 * @param idnb
	 * @return
	 */
	public static String getPcdIdnb(String idnb) {
		String pcdIdnb = "";
		if (!nullToString(idnb).equals("")) {
			if (idnb.length() > 16) {
				pcdIdnb = idnb.substring(0, 16);
			}
		}
		return pcdIdnb;
	}

	/**
	 * OBJECT为检查null值，如果为null，将返回一位空格的字符串" "，
	 * 
	 * @param strn
	 * @return
	 * 
	 * @pdOid a9ab0da9-e381-4966-b48e-d48c5abe32f3
	 */
	public static Object objectNullToString(Object obj) {
		if (obj == null)
			obj = "";
		return obj;
	}

	/**
	 * 判断DOUBLE类型的参数是不是为0或者NULL 是返回TRUE 反而FLASE
	 * 
	 * @param strn
	 * @return
	 * 
	 * @pdOid a9ab0da9-e381-4966-b48e-d48c5abe32f3
	 */
	public static boolean isZeroDouble(Double obj) {
		if (obj == null)
			return true;
		else if (obj == 0)
			return true;
		else
			return false;
	}

	/**
	 * 通过传入的数值型参数计算其和
	 * 
	 * @param str
	 * @return
	 */
	public static double getSumByString(String str) {
		double sum = 0.00;
		String arg[] = null;
		if (str != null) {
			arg = str.split(",");
			if (arg != null && arg.length > 0) {
				for (int i = 0; i < arg.length; i++) {
					sum += Double.parseDouble(arg[i]);
				}
			}
		}
		return sum;
	}

	/**
	 * 转码
	 * 
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String CharSet(String str, String charsetstr) throws UnsupportedEncodingException {
		String test = new String(str.getBytes("ISO8859-1"), charsetstr);
		System.out.println(str + "==" + test);
		return test;
	}

	/**
	 * 对格式化过的金额进行处理
	 * 
	 * @param money
	 * @return
	 */
	public static String MoneyUnFormat(String money) {
		DecimalFormat df = new DecimalFormat("####################0.00");
		if (money == null || money.trim().equals("")) {
			return "0.00";
		} else {
			money = money.trim();
		}
		if (money.contains("RMB")) {
			money = money.substring(3);
		}
		money = df.format(new BigDecimal(money).divide(new BigDecimal(100)));

		return money;
	}

	/**
	 * 格式化金额 带小数位
	 * 
	 * @param money
	 * @return
	 */
	public static String moneyFormat(String money) {
		if (money == null || money.trim().equals("")) {
			money = "0.00";
		} else {
			money = money.trim();
		}
		if (money.contains("RMB")) {
			// money=money.substring(3);
			return MoneyUnFormat(money);
		}
		if (money.contains("+") || money.contains("-")) {
			// money=money.substring(3);
			return money;
		}
		// System.out.println("money=============="+money);
		DecimalFormat df = new DecimalFormat("####################0.00");
		money = df.format(new BigDecimal(money));

		return money;
	}

	public static boolean isAmount(String cname) {
		for (int i = 0; i < mountUtils.length; i++) {
			if (mountUtils[i].equalsIgnoreCase(cname)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 提供精确的加法运算。
	 * 
	 * @param v1
	 *            被加数
	 * @param v2
	 *            加数
	 * @return 两个参数的和
	 */
	public static String add(String v1, String v2) {
		String money = "0.00";
		if ("".equals(StringUtils.nullToString(v1))) {
			v1 = "0.00";
		}
		if ("".equals(StringUtils.nullToString(v2))) {
			v2 = "0.00";
		}
		BigDecimal b1 = new BigDecimal(v1);
		BigDecimal b2 = new BigDecimal(v2);
		DecimalFormat df = new DecimalFormat("###,###,###,###,###,###,##0.00");
		money = df.format(b1.add(b2));
		return money;
	}

	/**
	 * 提供精确的减法运算。
	 * 
	 * @param v1
	 *            被减数
	 * @param v2
	 *            减数
	 * @return 两个参数的差
	 */
	public static String sub(String v1, String v2) {
		String money = "0.00";
		if ("".equals(StringUtils.nullToString(v1))) {
			v1 = "0.00";
		}
		if ("".equals(StringUtils.nullToString(v2))) {
			v2 = "0.00";
		}
		BigDecimal b1 = new BigDecimal(v1);
		BigDecimal b2 = new BigDecimal(v2);
		DecimalFormat df = new DecimalFormat("###,###,###,###,###,###,##0.00");
		money = df.format(b1.subtract(b2));
		return money;
	}

	/* *
	 * 指定编码按字节截取指定长度 （兼容中文乱码）
	 */
	public static String subStringByEncodedByte(String str, int len, String encoded) {
		StringBuilder sb = new StringBuilder();
		try {
			if (str != null) {
				int currentLength = 0;
				for (char c : str.toCharArray()) {
					currentLength += String.valueOf(c).getBytes(encoded).length;
					if (currentLength <= len) {
						sb.append(c);
					} else {
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	/**
	 * 
	 * 描述 : 按照字符编码截取Str的长度，超过的情况下，添加addStr. <br/>
	 * <p>
	 * 
	 * @param str
	 *            需要截取的字符串
	 * @param addStr
	 *            末尾添加的字符串
	 * @param len
	 *            需要截取的字符串的长度
	 * @param encoded
	 *            字符编码
	 * @return
	 */
	public static String sbuStringByEncodedByteAddSplit(String str, String addStr, int len, String encoded) {
		StringBuilder sb = new StringBuilder();
		String encodedStr = subStringByEncodedByte(str, len, encoded);
		try {
			sb.append(encodedStr);
			if (str.getBytes(encoded).length > len) {
				sb.append(addStr);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

}
